﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using YinfangWeb.BLL;
using YinfangWeb.BLL.Enum;
using YinfangWeb.BLL.Model;
using YinfangWeb.MLog;
using YinfangWeb.Model;

namespace YinfangWeb.Api.Controllers
{
    public class ProductController : ApiController
    {
        #region 添加商品
        /// <summary>
        /// 添加商品
        /// </summary>
        /// <param name="token"></param>
        /// <returns>返回新商品的序号(id)和编号(no)</returns>
        /// 1：src\views\product\add\index.vue
        [HttpPost]
        [ValidToken]
        [ValidRole(EnumUserRole.Manager)]
        [ValidRight(EnumUserRight.Product_Create)]
        public IHttpActionResult AddSpRecord(string token,int identity, [FromBody]JObject obj)
        {
            dynamic record = obj;
            if (record == null) return Json(new Result(ResultCode.ParameterMissing));
            string resStr = "添加";
            try
            {
                var ut = new UserBO().GetUserInfoByToken(token);
                ProductData data = _GetProductData(ut.UserDataID, ut.UserName, record);
                ProductParam param = _GetProductParam(record);
                if (data.ProductDataID > 0)
                {
                    resStr = "保存";
                }
                var result = new ProductBO().CreateProduct(data, param);
                return Json(result);
            }
            catch (Exception ex)
            {
                Logger.Default.Error(resStr+ "商品出错！", ex);
                return Json(new Result(ResultCode.Busy, ex.Message));
            }
        }
        private ProductData _GetProductData(int userId,string userName, dynamic record)
        {
            var pData = new ProductData
            {
                ProductDataID=record.id, //添加时自动，修改时是大于0的。 正式库需要从11110001起
                ProductState = record.state,//(int)EnumProductData_ProductState.Draft,//状态
                MerchantDataID = record.merchant_id,//商家ID - 必需
                ProductType = record.type,//商品类型:赠品、超市 - 必需
                ProductKindID = record.kind_id,//商品种类 - 必需
                ProductName = record.name,//商品名称 - 必需
                //ProductInfo //产品介绍-后面单独输入
                LinkURL = record.link_url ?? string.Empty,//比价链接
                SellBase = record.sell_base ?? 0,//虚拟销量(销量基数)
                IsActivity = record.is_activity ?? false,//活动商品
                IsRecommend = record.is_recommend ?? false,//推荐商品
                IsTop = record.is_top ?? false,//置顶
                IsMustbuy = record.is_must_buy ?? false,//必购
                LimitMonth = record.limit_month_num ?? 0,//月有限购      
                TotalStock= record.stock ?? 0,//当前库存
                EditDateTime = DateTime.Now,//修改时间
                EditUserID = userId,//修改人ID
                EditFullName = userName//修改人姓名
            };
            //添加时记录添加人信息
            if (pData.ProductDataID == 0)
            {
                pData.RegDateTime = DateTime.Now;//登记时间
                pData.RegUserID = userId;//登记人ID
                pData.RegFullName = userName;//登记人姓名
            }
            return pData;
        }
        private ProductParam _GetProductParam(dynamic record)
        {
            var pParam = new ProductParam
            {
                ProductParamID=record.param_id,  //序号-自动
                ProductDataID=record.id,   //产品序号-新增时写入时填入
                ParamDefault = (int)EnumProductParam_ParamDefault.Yes,//参数母版 - 0不是 1是(同个ProductDataID有且仅有一个) 母版无参数名称，无参数值
                OrderNum = 0,//排序号
                //ParamName1  //参数名称1
                //ParamValue1 //参数值1
                //ParamName2  //参数名称2
                //ParamValue2 //参数值2
                //ParamName3  //参数名称3
                //ParamValue3 //参数值3
                PriceMarket = record.price_market,//市场价 - 必需
                PriceSell=record.price_sell,//销售价 - 必需
                PriceNet = record.price_net,//裸价 - 必需
                PriceTax = record.price_tax ?? 0,//税费
                PricePost = record.price_post ?? 0,//运费
                PriceCost = record.price_cost,//成本价 - 必需
                CoinDeduct = record.coin_deduct ?? 0,//抵扣币值(积分)
                Stock = record.stock ?? 0,//当前库存
                //SellSum  //真实销量 - 在销售过程中填入
                //DefaultProductFileID //默认Logo - 上传展示图片时填入
            };
            return pParam;
        }
        #endregion
        #region 保存商品Logo图片列表
        /// <summary>
        /// 保存商品Logo图片列表
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        /// 1：src\views\product\add\dlg_update.vue
        [HttpPost]
        [ValidToken]
        [ValidRole(EnumUserRole.Manager)]
        [ValidRight(EnumUserRight.Product_Update)]
        public IHttpActionResult UpdateProductLogoList(string token,[FromBody]JObject obj)
        {
            dynamic model = obj;
            if (model == null || model.id == null) return Json(new Result(ResultCode.ParameterMissing));
            int id = model.id ?? 0;
            List<string> logoList = model.logo_list.ToObject<List<string>>();
            if (id < 1) return Json(new Result(ResultCode.ParameterError));
            //if(logoList.Count<=0) return Json(new Result(ResultCode.ListIsEmpty));
            try
            {
                var result = new ProductBO().UpdateProductLogoList(id,logoList);
                return Json(result);
            }
            catch (Exception ex)
            {
                Logger.Default.Error("保存商品Logo图片列表出错！", ex);
                return Json(new Result(ResultCode.Busy, ex.Message));
            }
        }
        #endregion
        #region 保存商品属性
        [HttpPost]
        [ValidToken]
        [ValidRole(EnumUserRole.Manager)]
        [ValidRight(EnumUserRight.Product_Create | EnumUserRight.Product_Update)]
        public IHttpActionResult SaveProductParamList(string token, [FromBody]JObject obj)
        {
            dynamic data = obj;
            if (data == null || data.sp_id==null || data.dc_type==null || data.type == null || data.list == null) return Json(new Result(ResultCode.ParameterMissing));
            try
            {
                int spId = data.sp_id;//商品ID
                int dcType = data.dc_type;//当前选中的属性类型：0无属性 1多属性
                int paramType = data.type;//属性个数
                List<ProductParam> paramList = data.list.ToObject<List<ProductParam>>();
                if (spId < 1 || paramType < 0 || paramType > 2 ||(dcType>0 && (paramType==0 || paramList.Count==0)))
                {
                    return Json(new Result(ResultCode.ParameterError));
                }
                var result = new ProductBO().SaveProductParamList(spId,dcType, paramType, paramList);
                return Json(new Result());
            }
            catch (Exception ex)
            {
                Logger.Default.Error("保存商品属性出错！", ex);
                return Json(new Result(ResultCode.Busy, ex.Message));
            }
        }
        #endregion
        #region 保存商品富文本
        public IHttpActionResult SaveProductHtml(string token,[FromBody]JObject obj) {
            dynamic data = obj;
            if (data == null ||data.sp_id==null || data.html == null) return Json(new Result(ResultCode.ParameterMissing));
            try
            {
                int id = data.sp_id;
                string html = data.html;                
                var result = new ProductBO().SaveProductHtml(id,html);
                return Json(result);
            }
            catch (Exception ex)
            {
                Logger.Default.Error("保存商品富文本出错！", ex);
                return Json(new Result(ResultCode.Busy, ex.Message));
            }
        }
        #endregion
        #region 设置商品状态
        public IHttpActionResult SetProductState(string token, [FromBody]JObject obj)
        {
            dynamic data = obj;
            if (data == null || data.sp_id == null || data.state == null) return Json(new Result(ResultCode.ParameterMissing));
            try
            {
                int id = data.sp_id;
                int state = data.state;
                if (id < 1 || state < 0 && state > 3) return Json(new Result(ResultCode.ParameterError));
                var result = new ProductBO().SetProductState(id, state);
                return Json(result);
            }
            catch (Exception ex)
            {
                Logger.Default.Error("设置商品状态出错！", ex);
                return Json(new Result(ResultCode.Busy, ex.Message));
            }
        }
        #endregion
        #region 保存新增或修改后的商品种类信息
        /// <summary>
        /// 保存新增或修改后的商品种类信息
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        /// 1：src\views\product\category\index\d_update.vue - M
        [HttpPost]
        [ValidToken]
        public IHttpActionResult SaveProductKind(string token, [FromBody]JObject obj)
        {
            dynamic data = obj;
            if (data == null || data.record == null || data.is_add == null) return Json(new Result(ResultCode.ParameterMissing));
            try
            {
                bool isAdd = data.is_add;
                var productKindInfo = _GetProductKindData(data.record);
                //new UserBO().get
                var result = new ProductBO().SaveProductKind(productKindInfo, isAdd);
                return Json(result);
            }
            catch (Exception ex)
            {
                Logger.Default.Error("保存新增或修改后的商品种类信息出错！", ex);
                return Json(new Result(ResultCode.Busy, ex.Message));
            }
        }
        private ProductKind _GetProductKindData(dynamic record)
        {
            return new ProductKind {
                ProductKindID=record.ProductKindID,
                KindName=record.KindName,
                KindLevel= record.KindLevel,
                KindState=record.KindState,
                OrderNum=record.OrderNum,
                RegUserID=1,
                RegFullName="admin",
                RegDateTime=DateTime.Now
            };
        }
        #endregion

        #region 获取商品分页列表
        /// <summary>
        /// 获取商品分页列表
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        /// 1：src\views\product\list\sp_table.vue - Manager
        /// 2: src\views\shoppinglist\index\c_splist.vue - Business
        [HttpPost]
        [ValidToken]
        [ValidRole(EnumUserRole.Manager|EnumUserRole.Business)]
        [ValidRight(EnumUserRight.Product_List)]
        public IHttpActionResult GetSpList(string token,int identity,[FromBody]JObject obj)
        {
            dynamic model = obj;
            if (model == null) return Json(new Result(ResultCode.ParameterMissing));
            try
            {
                int pageIndex = model.page_index ?? 0;
                int pageSize = model.page_size ?? 0;
                if(pageIndex<1 || pageSize<1) return Json(new Result(ResultCode.ParameterError));
                var wc = _GetWhereC(model.condidate);
                var result = new ProductBO().GetSpList(pageIndex,pageSize,wc);
                return Json(result);
            }
            catch (Exception ex)
            {
                Logger.Default.Error("获取商品分布页表出错！", ex);
                return Json(new Result(ResultCode.Busy, ex.Message));
            }
        }
        private string _GetWhereC(dynamic qc)
        {
            if (qc == null) return string.Empty;
            int tInt = 0;
            string tStr = string.Empty;
            string wc = string.Empty;
            //商品类型：isMarket  true-超市商品  false-赠品
            bool isMarket = qc.is_market ?? false;
            wc = $"pd.ProductType={(isMarket?2:1)}";
            return wc;
        }
        #endregion
        #region 获取商品编辑信息-含基本信息、logo列表 - &Business
        /// <summary>
        /// 获取商品编辑信息
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        /// 1：src\views\product\add\index.vue
        /// 2：src\views\shoppingselect\index.vue - Business
        [HttpPost]
        [ValidToken]
        [ValidRole(EnumUserRole.Manager)]
        [ValidRight(EnumUserRight.Product_Update)]
        public IHttpActionResult GetProductEditInfo(string token,[FromBody]JObject obj)
        {
            dynamic model = obj;
            if (model == null || model.id == null) return Json(new Result(ResultCode.ParameterMissing));
            int id = model.id ?? 0;
            if(id<1) return Json(new Result(ResultCode.ParameterError));
            try
            {
                var result = new ProductBO().GetProductEditInfo(id);
                return Json(result);
            }
            catch (Exception ex)
            {
                Logger.Default.Error("获取商品编辑信息出错！", ex);
                return Json(new Result(ResultCode.Busy, ex.Message));
            }
        }
        #endregion
        #region 获取商品展示图片列表
        /// <summary>
        /// 获取商品展示图片列表
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        /// 1：src\views\product\add\index.vue
        [HttpPost]
        [ValidToken]
        [ValidRole(EnumUserRole.Manager)]
        [ValidRight(EnumUserRight.Product_Update)]
        public IHttpActionResult GetProductShowPicList(string token, [FromBody]JObject obj)
        {
            dynamic model = obj;
            if (model == null || model.id == null) return Json(new Result(ResultCode.ParameterMissing));
            int id = model.id ?? 0;
            if (id < 1) return Json(new Result(ResultCode.ParameterError));
            try
            {
                var result = new ProductBO().GetProductShowPicList(id);
                return Json(result);
            }
            catch (Exception ex)
            {
                Logger.Default.Error("获取商品展示图片列表出错！", ex);
                return Json(new Result(ResultCode.Busy, ex.Message));
            }
        }
        #endregion
        #region 获取商品图标列表
        /// <summary>
        /// 获取商品图标列表
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        /// 1：src\views\product\add\index.vue
        [HttpPost]
        [ValidToken]
        [ValidRole(EnumUserRole.Manager)]
        [ValidRight(EnumUserRight.Product_Update)]
        public IHttpActionResult GetProductLogoSelectList(string token, [FromBody]JObject obj)
        {
            dynamic model = obj;
            if (model == null || model.id == null) return Json(new Result(ResultCode.ParameterMissing));
            int id = model.id ?? 0;
            if (id < 1) return Json(new Result(ResultCode.ParameterError));
            try
            {
                var result = new ProductBO().GetProductLogoSelectList(id);
                return Json(result);
            }
            catch (Exception ex)
            {
                Logger.Default.Error("获取商品图标列表出错！", ex);
                return Json(new Result(ResultCode.Busy, ex.Message));
            }
        }
        #endregion
        #region 获取商品属性参数列表 - &Business
        /// <summary>
        /// 获取商品属性参数列表
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        /// 1：src\views\product\add\index.vue
        /// 2：src\views\shoppingselect\index.vue - Business
        [HttpPost]
        [ValidToken]
        [ValidRole(EnumUserRole.Manager)]
        [ValidRight(EnumUserRight.Product_Update)]
        public IHttpActionResult GetProductAttrParamList(string token, [FromBody]JObject obj)
        {
            dynamic model = obj;
            if (model == null || model.id == null) return Json(new Result(ResultCode.ParameterMissing));
            int id = model.id ?? 0;
            if (id < 1) return Json(new Result(ResultCode.ParameterError));
            try
            {
                var result = new ProductBO().GetProductAttrParamList(id);
                return Json(result);
            }
            catch (Exception ex)
            {
                Logger.Default.Error("获取商品属性参数列表出错！", ex);
                return Json(new Result(ResultCode.Busy, ex.Message));
            }
        }
        #endregion
        #region 获取商品富文本
        /// <summary>
        /// 获取商品富文本
        /// </summary>
        /// <param name="token"></param>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult GetProductHtml(string token, [FromBody]JObject obj)
        {
            dynamic data = obj;
            if (data == null || data.sp_id == null) return Json(new Result(ResultCode.ParameterMissing));
            try
            {
                int id = data.sp_id;
                var result = new ProductBO().GetProductHtml(id);
                return Json(result);
            }
            catch (Exception ex)
            {
                Logger.Default.Error("获取商品富文本出错！", ex);
                return Json(new Result(ResultCode.Busy, ex.Message));
            }
        }
        #endregion
        #region 获取商品种类选择列表
        /// <summary>
        /// 获取商品种类选择列表
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        /// 1：src\components\BasicType\select_product_kind.vue - M
        [HttpPost]
        public IHttpActionResult GetProductKindSelectList(string token, [FromBody]JObject obj)
        {
            dynamic data = obj;
            if (data == null || data.type == null) return Json(new Result(ResultCode.ParameterMissing));
            try
            {
                EnumProductData_ProductType prodType = data.type;
                var result = new ProductBO().GetProductKindSelectList(prodType);
                return Json(result);
            }
            catch (Exception ex)
            {
                Logger.Default.Error("获取商品种类选择列表出错！", ex);
                return Json(new Result(ResultCode.Busy, ex.Message));
            }
        }
        #endregion
        #region 获取商品种类编辑列表
        /// <summary>
        /// 获取商品种类编辑列表
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        /// 1：src\views\product\category\index\c_table.vue - M
        [HttpPost]
        public IHttpActionResult GetProductKindEditList(string token, [FromBody]JObject obj)
        {
            dynamic data = obj;
            if (data == null || data.type == null) return Json(new Result(ResultCode.ParameterMissing));
            try
            {
                EnumProductData_ProductType prodType = data.type;
                EnumProductKind_KindLevel kindLevel = data.level;
                var result = new ProductBO().GetProductKindEditList(prodType, kindLevel);
                return Json(result);
            }
            catch (Exception ex)
            {
                Logger.Default.Error("获取商品种类编辑列表出错！", ex);
                return Json(new Result(ResultCode.Busy, ex.Message));
            }
        }
        #endregion
        #region 获取添加商品种类初始信息
        /// <summary>
        /// 获取添加商品种类初始信息
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        /// 1：src\views\product\category\index\d_update.vue - M
        [HttpPost]
        public IHttpActionResult GetProductKindAddInitInfo(string token, [FromBody]JObject obj)
        {
            dynamic data = obj;
            if (data == null || data.type == null) return Json(new Result(ResultCode.ParameterMissing));
            try
            {
                EnumProductData_ProductType prodType = data.type;
                var result = new ProductBO().GetProductKindAddInitInfo(prodType);
                return Json(result);
            }
            catch (Exception ex)
            {
                Logger.Default.Error("获取添加商品种类初始信息出错！", ex);
                return Json(new Result(ResultCode.Busy, ex.Message));
            }
        }
        #endregion

        #region 获取商品卡片分页列表 - Business
        /// <summary>
        /// 获取商品分页列表
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        /// 1: src\views\shoppinglist\index\c_splist.vue - Business
        [HttpPost]
        [ValidToken]
        [ValidRole(EnumUserRole.Manager | EnumUserRole.Business)]
        [ValidRight(EnumUserRight.Product_List)]
        public IHttpActionResult GetSpCardList(string token, [FromBody]JObject obj)
        {
            dynamic model = obj;
            if (model == null) return Json(new Result(ResultCode.ParameterMissing));
            try
            {
                int pageIndex = model.page_index ?? 0;
                int pageSize = model.page_size ?? 0;
                if (pageIndex < 1 || pageSize < 1) return Json(new Result(ResultCode.ParameterError));

                var result = new ProductBO().GetSpCardList(pageIndex, pageSize);
                return Json(result);
            }
            catch (Exception ex)
            {
                Logger.Default.Error("获取商品分布页表出错！", ex);
                return Json(new Result(ResultCode.Busy, ex.Message));
            }
        }
        #endregion
        #region 获取商城首页各类列表 - Business
        /// <summary>
        /// 获取商城首页各类列表 - Business
        /// </summary>
        /// <param name="token"></param>
        /// <param name="identity"></param>
        /// <returns></returns>
        public IHttpActionResult GetMarketList(string token,int identity)
        {
            try
            {
                var result = new ProductBO().GetMarketList();
                return Json(result);
            }
            catch (Exception ex)
            {
                Logger.Default.Error("获取商城首页各类列表(Business)出错！", ex);
                return Json(new Result(ResultCode.Busy, ex.Message));
            }
        }
        #endregion
    }
}
